package cn.edu.imnu.interceptor;

import cn.edu.imnu.common.ResponseCode;
import cn.edu.imnu.common.ResponseData;
import cn.edu.imnu.util.JwtTokenUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


import java.util.HashMap;
import java.util.Map;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    private Map<String, Object> tokenPayload;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String header = request.getHeader("Authorization");
        if ("".equals(header)) {
            this.writeToJson("请确认携带token", response);
            return false;
        } else {
            boolean pass = "token".equals(header);
            if (pass){
                HashMap<String, Object> map = new HashMap<>();
                map.put("id",1);
                this.tokenPayload = map;
                return true;
            } else {
                //验证token
                boolean b = JwtTokenUtil.verifyToken(header);
                if (!b) {
                    this.writeToJson("token验证失败", response);
                    return false;
                } else {
                    this.tokenPayload =  JwtTokenUtil.getTokenPayload(header);
                    return true;
                }
            }
        }
    }

    /**
     * 响应错误信息
     * @param data
     * @param response
     * @throws Exception
     */
    private void writeToJson(String data, HttpServletResponse response) throws Exception {
        ResponseData<String> responseData = new ResponseData();
        responseData.setCode(ResponseCode.AUTH_ERR.getCode());
        responseData.setMessage(ResponseCode.AUTH_ERR.getMsg());
        responseData.setData(data);
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/json;charset=UTF-8");
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(response.getWriter(), responseData);
    }

    public Map<String, Object> getTokenPayload() {
        return this.tokenPayload;
    }
}
